package com.lz.helper.idcard

import android.content.Context
import android.util.Log
import com.mx.finger.api.msc.MxIdMscFingerApiFactory

//新像素指纹识别
class NxsFingerRequest(
    context: Context,
    matcher: ByteArray,
    threshold: Float,
    handler: FingerHandler
) : FingerRequest(context, matcher, threshold, handler) {

    override fun run() {
        Log.d(TAG, "...... NxsFingerRequest thread start ......")
        val fingerFactory = MxIdMscFingerApiFactory(context)

        val api = fingerFactory.api
        if (api.deviceInfo?.isSuccess != true) {
            handler.sendFingerError(OPEN_FAIL)
            return
        }
        handler.sendFingerOpenSuccess()
        val alg = fingerFactory.alg
        while (!isQuit()) {
            await()
            if (isQuit()) break
            val result = api.detectFinger()
            if (result?.isSuccess != true) {
//                Log.d(TAG, "detectFinger fail ...")
                errAndDelay(ERR_IMAGE, 1000)
                continue
            }

            val mxImageResult = api.getFingerImageBig(500)
            if (isQuit()) break
            if (mxImageResult?.isSuccess != true) {
//                Log.d(TAG, "getFingerImageBig fail ...")
                errAndDelay(ERR_UN_PRESS, 500)
                continue
            }

            val image = mxImageResult.data!!
            val feature = alg.extractFeature(image.data, image.width, image.height)
            if (isQuit()) break
            if (feature == null || feature.isEmpty()) {
//                Log.d(TAG, "extractFeature err ...")
                errAndDelay(ERR_MATCHING)
                continue
            }

            val match = alg.match(matcher, feature, 4)
            if (isQuit()) break
            if (match != 0) {
//                Log.d(TAG, "match err ...")
                errAndDelay(ERR_MATCHING)
                continue
            }
            handler.sendFingerResult(100)
            break
        }
        Log.d(TAG, "...... NxsFingerRequest thread quit ......")
    }

    //延时处理
    private fun errAndDelay(err: Int, timeMs: Long = 1000L) {
        handler.sendFingerError(err)
        delay(timeMs)
    }
}